package com.ljl;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * @author ljl
 * @version 1.0
 * @date 2022/10/26 9:08
 */
public class MinaClient {

    public static void main(String[] args) {
        String host = "127.0.0.1";
        int port = 7036;
        NioSocketConnector socketConnector = new NioSocketConnector();
        //保持tcp连接
        socketConnector.getSessionConfig().setKeepAlive(true);
        //设置编解码器
        socketConnector.getFilterChain().addLast("codec", new ProtocolCodecFilter(
                new TextLineCodecFactory(
                        Charset.forName("gbk"),
                        LineDelimiter.WINDOWS.getValue(),
                        LineDelimiter.WINDOWS.getValue()
                )
        ));
        socketConnector.setHandler(new ClientHandler());

        ConnectFuture future = socketConnector.connect(new InetSocketAddress(host, port));
        //等待连接成功
        future.awaitUninterruptibly();
        System.out.println("连接成功！");
        //等待连接断开
        IoSession session = future.getSession();
        session.getCloseFuture().awaitUninterruptibly();
        //资源清理
        socketConnector.dispose();
    }

}
